package cn.drenal.capcap.config;

import cn.drenal.capcap.entity.SysAdmin;
import cn.drenal.capcap.entity.SysAdminRole;
import cn.drenal.capcap.mapper.SysAdminMapper;
import cn.drenal.capcap.mapper.SysAdminRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.dev33.satoken.secure.SaSecureUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;

/**
 * 系统初始化配置
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class InitConfig implements CommandLineRunner {

    private final SysAdminMapper sysAdminMapper;
    private final SysAdminRoleMapper sysAdminRoleMapper;

    @Override
    public void run(String... args) {
        // 检查是否存在默认管理员账号
        SysAdmin admin = sysAdminMapper.selectOne(
                new LambdaQueryWrapper<SysAdmin>()
                        .eq(SysAdmin::getUsername, "super_admin")
        );

        // 如果不存在，则创建默认管理员账号
        if (admin == null) {
            admin = new SysAdmin();
            admin.setUsername("super_admin");
            admin.setPassword(SaSecureUtil.md5(SaSecureUtil.md5("Admin1234!")));
            admin.setNickname("超级管理员");
            admin.setStatus(1);
            admin.setRole("super-admin");
            sysAdminMapper.insert(admin);
            
            // 创建管理员与角色的关联记录
            SysAdminRole adminRole = new SysAdminRole();
            adminRole.setUserId(admin.getId());
            adminRole.setRoleId(1L); // 超级管理员角色ID为1
            sysAdminRoleMapper.insert(adminRole);
            
            log.info("创建默认管理员账号及角色关联成功");
        }
    }
}